<?php
namespace app\farm\controller;
use app\ApiRest;


use app\farm\model\AboutUs;
use app\farm\model\Article;
use app\farm\model\Banner;
use app\farm\model\Car;
use app\farm\model\ClaimOrder;
use app\farm\model\Coupon;
use app\farm\model\CouponRecord;
use app\farm\model\Evaluate;
use app\farm\model\LandOrder;
use app\farm\model\LandText;
use app\farm\model\Monitor;
use app\farm\model\MonitorText;
use app\farm\model\ShopGoods;
use app\farm\model\WelfareColumn;

use app\massage\model\Config;



use app\farm\model\Address;

use app\farm\model\User;

use app\publics\model\TmplConfig;

use longbingcore\wxcore\YsCloudApi;
use think\App;
use think\facade\Db;
use think\Request;


class Index extends ApiRest
{

    protected $model;


    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new User();


    }


    /**
     * @author chenniang
     * @DataTime: 2022-03-02 16:58
     * @功能说明:首页
     */
    public function index(){

        $input = $this->_param;

        $config_model = new \app\farm\model\Config();

        $data['weather'] = $config_model->getPlaceWeather();

        $arr = [
            //轮播
            1 => 'rotation',
            //广告
            2 => 'poster'
        ];

        $banner_model = new Banner();

        foreach ($arr as $k=>$v){

            $dis = [

                'type'    => $k,

                'status'  => 1,

                'uniacid' => $this->_uniacid
            ];

            $data['banner'][$v] = $banner_model->where($dis)->order('top desc,id desc')->select()->toArray();
        }

        $where[] = ['uniacid','=',$this->_uniacid];

        $where[] = ['status','=',1];

        $where[] = ['type','=',0];

        $us_model = new AboutUs();

        $about = $us_model->dataInfo($where);
        //收否有关于我们
        $data['about_us'] = !empty($about)?1:0;

        $dis = [

            'uniacid' => $this->_uniacid,

            'status'  => 2,

            'type'    => 2,

            'business_status' => 1
        ];

        $farmer_model = new \app\farm\model\Farmer();

        $lat = !empty($input['lat'])?$input['lat']:0;

        $lng = !empty($input['lng'])?$input['lng']:0;

        $alh = '(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*('.$lng.'- `lng`)/360),2)+COS(PI()*33.07078170776367/180)* COS('.$lat.' * PI()/180)*POW(SIN(PI()*('.$lat.'- lat)/360),2))))*1000 as distance';
        //门店列表
        $store = $farmer_model->where($dis)->field(['*',$alh])->order('distance,id desc')->limit(3)->select()->toArray();

        if(!empty($store)){

            foreach ($store as &$v){

                $v['distance'] = getDistances($v['lng'],$v['lat'],$lng,$lat);

                $v['distance'] = $farmer_model->getDistanceAttr($v['distance']);

            }

        }

        $data['store_list'] = $store;

        $arr = [

            1 => 'welfare_list',

            2 => 'system_list'
        ];

        $welfare_model = new WelfareColumn();

        foreach ($arr as  $k=>$value){

            $dis = [

                'uniacid' => $this->_uniacid,

                'status'  => 1,

                'type'    => $k
            ];

            $data[$value] = $welfare_model->where($dis)->order('top desc,id desc')->limit(5)->select()->toArray();

        }

        $goods_model = new ShopGoods();

        $dis = [

            'uniacid' => $this->_uniacid,

            'index_show' => 1,

            'status'  => 1
        ];

        $data['hot_goods'] = $goods_model->where($dis)->order('top desc,id desc')->limit(3)->select()->toArray();

        return $this->success($data);
    }









    /**
     * @author chenniang
     * @DataTime: 2022-02-18 16:41
     * @功能说明:获取天气
     */
    public function weather(){

        $input = $this->_param;

        $dis = [

            'uniacid' => $this->_uniacid
        ];

        $config_model = new Config();

        $config = $config_model->dataInfo($dis);

        $url  = 'https://apis.map.qq.com/ws/geocoder/v1/?location='.$input['lat'].','.$input['lng'];

        $url  = $url.'&key='.$config['map_secret'];

        $location = longbingCurl($url,[]);

        $location = json_decode($location,true);

        $data['weather'] = [];

        if(!empty($location['result']['address_component'])){

            $location = $location['result']['address_component'];

            if(!empty($location['province'])){

                $province = $location['province'];

                $city     = $location['city'];

                $county   = $location['district'];

                $url = 'https://wis.qq.com/weather/common?source=pc&weather_type=observe|forecast_24h|air&province='.$province.'&city='.$city.'&county='.$county;

                $weather = file_get_contents($url);

                $weather = @json_decode($weather,true);
                //天气
                $data['weather'] = $weather;
            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 14:16
     * @功能说明:获取配置信息
     */
    public function configInfo(){

        $dis = [

            'uniacid' => $this->_uniacid
        ];

        $config_model = new Config();

        $config = $config_model->dataInfo($dis);

        return $this->success($config);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-12-30 15:21
     * @功能说明:
     */
    public function farmerSelectList(){

        $dis = [

            'uniacid' => $this->_uniacid,

            'status'  => 2,

            'type'    => 1
        ];

        $farmer_model = new \app\farm\model\Farmer();

        $data = $farmer_model->where($dis)->select()->toArray();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-07 14:35
     * @功能说明:农场列表
     */
    public function farmerList(){

        $input = $this->_param;


        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['status','=',2];

        $dis[] = ['type','=',1];

        if(!empty($input['title'])){

            $dis[] = ['title','like','%'.$input['title'].'%'];

        }

        $sort = !empty($input['sort'])?$input['sort']:2;

        $farmer_model = new \app\farm\model\Farmer();

        $lat = !empty($input['lat'])?$input['lat']:0;

        $lng = !empty($input['lng'])?$input['lng']:0;

        $alh = '(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*('.$lng.'- `lng`)/360),2)+COS(PI()*33.07078170776367/180)* COS('.$lat.' * PI()/180)*POW(SIN(PI()*('.$lat.'- lat)/360),2))))*1000 as distance';

        switch ($sort){

            case 1:

                $top = 'id desc';

                break;

            case 2:

                $top = 'distance,id desc';

                break;

            case 3:

                $top = 'iv desc,id desc';

                break;
        }

        $data = $farmer_model->where($dis)->field(['*',$alh])->order($top)->paginate(10)->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $dis = [

                    'type'    => 2,

                    'user_id' => $v['user_id'],

                    'uniacid' => $this->_uniacid
                ];

                $v['store_id'] = $farmer_model->where($dis)->value('id');
            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-07 14:43
     * @功能说明:农场详情
     *
     */
    public function farmerInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $farmer_model = new \app\farm\model\Farmer();

        $data = $farmer_model->dataInfo($dis);

        $farmer_model->dataUpdate($dis,['iv'=>$data['iv']+1]);

        $dis = [

            'type'    => 2,

            'user_id' => $data['user_id'],

            'uniacid' => $this->_uniacid
        ];

        $data['store_id'] = $farmer_model->where($dis)->value('id');

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-06 15:21
     * @功能说明:文章详情
     */
    public function articleInfo(){

        $input = $this->_param;

        $article_model = new Article();

        $data = $article_model->dataInfo(['id'=>$input['article_id']]);

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-30 11:51
     * @功能说明:关于我们列表
     */
    public function aboutUsList(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['status','=',1];

        $dis[] = ['type','=',0];

        if(!empty($input['title'])){

            $dis[] = ['title','like','%'.$input['title'].'%'];
        }

        $us_model = new AboutUs();

        $data = $us_model->where($dis)->order('top desc,id desc')->limit(10)->select()->toArray();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-08 13:23
     * @功能说明:我们列表详情
     */
    public function aboutUsInfoType(){

        $input = $this->_param;

        $input['type'] = !empty($input['type'])?$input['type']:0;

        $dis = [

            'type'=> $input['type'],

            'uniacid' => $this->_uniacid
        ];

        $us_model = new AboutUs();

        $res = $us_model->dataInfo($dis);

        if(!empty($input['type'])&&empty($res)){

            $title = $input['type']==1?'动物认养协议':'土地租赁协议';

            $dis['title'] = $title;

            $us_model->dataAdd($dis);

            $res = $us_model->dataInfo($dis);
        }

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2022-02-09 17:07
     * @功能说明:添加评价
     */
    public function evaluateAdd(){

        $input = $this->_input;

        $eva_model = new Evaluate();

        $dis = [

            'order_id' => $input['order_id'],

            'type'     => $input['type']
        ];

        $find = $eva_model->where($dis)->where('status','>',-1)->find();

        if(!empty($find)){

            $this->errorMsg('你已经评价过该订单了');
        }

        $insert = [

            'uniacid' => $this->_uniacid,

            'user_id' => $this->getUserId(),

            'order_id'=> $input['order_id'],

            'star'    => $input['star'],

            'type'    => $input['type'],

            'order_code'=> $input['order_code'],

            'text'      => $input['text'],

            'imgs'      => !empty($input['imgs'])?implode(',',$input['imgs']):'',

            'farmer_id' => !empty($input['farmer_id'])?$input['farmer_id']:0,

        ];

        $res = $eva_model->dataAdd($insert);
        //修改农场主的评分
        $res = $eva_model->updateFarmerStar($input['farmer_id']);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-09 17:17
     * @功能说明:用户评列表
     */
    public function userEvaluateList(){

        $input = $this->_param;

        $eva_model = new Evaluate();

        $dis[] = ['user_id','=',$this->getUserId()];

        $dis[] = ['status','>',-1];

        if(!empty($input['type'])){

            $dis[] = ['type','=',$input['type']];

        }

        $data = $eva_model->dataList($dis);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

                if(!empty($v['order_info']['end_time'])){

                    $v['order_info']['end_time'] = date('Y-m-d H:i:s',$v['order_info']['end_time']);

                }

            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-09 17:21
     * @功能说明:评价详情
     */
    public function evaluateInfo(){

        $input = $this->_param;

        $eva_model = new Evaluate();

        $dis =[

            'id' => $input['id']
        ];

        $data = $eva_model->dataInfo($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-09 17:21
     * @功能说明:评价详情
     */
    public function evaluateUpdate(){

        $input = $this->_input;

        $eva_model = new Evaluate();

        $dis =[

            'id' => $input['id']
        ];

        $info = $eva_model->dataInfo($dis);

        $data = $eva_model->dataUpdate($dis,$input);

        if(!empty($input['status'])&&$input['status']==-1){
            //修改农场主的评分
            $res = $eva_model->updateFarmerStar($info['farmer_id']);
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-10 17:23
     * @功能说明:待评价订单
     */
    public function noEvaluateOrderList(){

        $input = $this->_param;

        $eva_model = new Evaluate();

        $model = $eva_model->getTypeModel($input['type']);

        $where = [

            'user_id' => $this->getUserId(),

            'type'    => $input['type']
        ];

        $order_id = $eva_model->where($where)->where('status','>',-1)->column('order_id');

        $dis[] = ['user_id','=',$this->getUserId()];

        if($input['type']==2){

            $dis[] = ['pay_type','>',1];

        }else{

            $dis[] = ['pay_type','=',7];
        }

        $dis[] = ['id','not in',$order_id];

        $data = $model->dataList($dis,10);

        if(!empty($data['data'])){

            $farmer_model = new \app\farm\model\Farmer();

            foreach ($data['data'] as &$v){

                $farmer_id = !empty($v['farmer_id'])?$v['farmer_id']:0;

                $v['farmer_info'] = $farmer_model->dataInfo(['id'=>$farmer_id],'title');

                if(!empty($v['end_time'])){

                    $v['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
                }

            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-11 10:11
     * @功能说明:根据type获取对应物品的评价
     */
    public function goodsEvaluateList(){

        $input = $this->_param;

        $eva_model = new Evaluate();

        $data = $eva_model->goodsEvaluateList($input['goods_id'],$input['type'],$input['is_goods']);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-03-09 16:50
     * @功能说明:模版列表
     */
    public function tmpList(){
        //模版消息model
        $tmpl_model = new TmplConfig();
        //获取模版
        $tmpl       = $tmpl_model->where(['uniacid'=>$this->_uniacid])->select()->toArray();

        return $this->success($tmpl);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-04-11 15:56
     * @功能说明:监控列表
     */
    public function monitorList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        if(!empty($input['farmer_id'])){

            $dis[] = ['a.farmer_id','=',$input['farmer_id']];

        }else{
            //我的菜地
            $land_model = new LandOrder();

            $claim_model= new ClaimOrder();

            $monitor_text_model = new MonitorText();

            $land_text_model = new LandText();

            $land_id = $land_model->where(['user_id'=>$this->getUserId()])->where('pay_type','>',1)->column('land_id');

            $obj_id  = $land_text_model->where('land_id','in',$land_id)->where(['type'=>4])->column('obj_id');

            $claim_id=  $claim_model->where(['user_id'=>$this->getUserId()])->where('pay_type','>',1)->column('goods_id');

            $obj_id_v2 = $monitor_text_model->where('obj_id','in',$claim_id)->where(['type'=>2])->column('monitor_id');

            $monitor_id = array_merge($obj_id,$obj_id_v2);

            $dis[] = ['a.id','in',$monitor_id];

        }

        $dis[] = ['a.status','=',1];

        if(!empty($input['title'])){

            $dis[] = ['a.title','like','%'.$input['title'].'%'];

        }

        $monitor_model = new Monitor();

        $data = $monitor_model->farmerMonitorList($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-04-11 16:31
     * @功能说明:获取监控地址
     */
    public function getMonitorInfo(){

        $input = $this->_param;

        $monitor_model = new Monitor();

        $data['url'] = $monitor_model->getVideoUrl($input['id']);

        $api = new YsCloudApi($this->_uniacid);

        $data['token'] = $api->getToken();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-04-12 11:01
     * @功能说明:获取萤石云token
     */
    public function getYsToken(){

        $api = new YsCloudApi($this->_uniacid);

        $token = $api->getToken();

        return $this->success($token);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-04-12 11:02
     * @功能说明:旋转摄像头
     */
    public function ysStartTurn(){

        $input = $this->_param;

        $monitor_model = new Monitor();

        $api = new YsCloudApi($this->_uniacid);

        $monitor = $monitor_model->dataInfo(['id'=>$input['id']]);

        $res = $api->startTurn($monitor['deviceSerial'],$input['direction'],$monitor['channelNo']);

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2022-04-12 11:02
     * @功能说明:停止旋转摄像头
     */
    public function ysStopTurn(){

        $input = $this->_param;

        $monitor_model = new Monitor();

        $api = new YsCloudApi($this->_uniacid);

        $monitor = $monitor_model->dataInfo(['id'=>$input['id']]);

        $direction = !empty($input['direction'])?$input['direction']:0;

        $res = $api->stopTurn($monitor['deviceSerial'],$direction,$monitor['channelNo']);

        return $this->success($res);

    }



    public function haveStore()
    {


        $data = $this->getStoreInfo(2);

        $res =  !empty($data)?true:false;

        return $this->success($res);


    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-22 17:34
     * @功能说明:公益列表
     */
    public function welfareColumnList(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['status','=',1];

        $type = !empty($input['type'])?$input['type']:1;

        $dis[] = ['type','=',$type];

        $model = new WelfareColumn();

        if(!empty($input['title'])){

            $dis[] = ['title','like','%'.$input['title'].'%'];

        }

        $data = $model->dataList($dis,10,'id,title,cover,create_time');

        return $this->success($data);

    }

    /**
     * @author chenniang
     * @DataTime: 2022-07-22 17:34
     * @功能说明:公益列表
     */
    public function welfareColumnInfo(){

        $input = $this->_param;

        $dis = [

            'id'     => $input['id'],

            'status' => 1
        ];

        $model = new WelfareColumn();

        $data = $model->dataInfo($dis);

        return $this->success($data);

    }




    /**
     * @author chenniang
     * @DataTime: 2022-06-15 16:29
     * @功能说明:优惠券
     */
    public function couponList(){

        $coupon_record_model = new CouponRecord();

        $coupon_model = new Coupon();

        if(empty($this->getUserId())){

            return $this->success([]);

        }

        $have_get = $coupon_record_model->where(['user_id'=>$this->getUserId()])->column('coupon_id');

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['send_type','=',2];

        $dis[] = ['status','=',1];

        $dis[] = ['stock','>',0];

        $dis[] = ['id','not in',$have_get];

        $where = [];

        $where[] = ['time_limit','=',2];

        $where[] = ['end_time','>',time()];

        $data = $coupon_model->where($dis)->where(function ($query) use ($where){
            $query->whereOr($where);
        })->paginate(10)->toArray();

        if(!empty($coupon['data'])){

            foreach ($coupon['data'] as &$v){

                $v['start_time'] = date('Y.m.d H:i',$v['start_time']).' - '.date('Y.m.d H:i',$v['end_time']);

            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-06-15 22:49
     * @功能说明:用户获取卡券
     */
    public function userGetCoupon(){

        $input = $this->_input;

        $coupon_record_model = new CouponRecord();

        $res = $coupon_record_model->recordAdd($input['coupon_id'],$this->getUserId(),1,1);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success(true);
    }




}
